#include "widget.h"
#include "ui_widget.h"


Start *T=NULL;
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->textBrowser->setText(title);
    //ui->textBrowser_2->setText("初始化成功");
    T=new Start;
    model=new QStandardItemModel(ui->treeView);
    ui->treeView->setModel(model);
    model->setHorizontalHeaderLabels(QStringList()<<"家族谱");

    scene = new QGraphicsScene(this);
    scene->setSceneRect(0, 0, 3000, 3000);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    ui->graphicsView->setDragMode(QGraphicsView::ScrollHandDrag);
    ui->graphicsView->setScene(scene);

}

Widget::~Widget()
{
    //这货是析构别写错了
    delete ui;
}


void Widget::on_Init_clicked()
{
    delete model;
    model=new QStandardItemModel(ui->treeView);
    ui->treeView->setModel(model);
    ui->Screen->clear();
    ui->textBrowser_2->setText("初始化成功");
    T=new Start;
}

QModelIndex Widget::findIndexByName(QStandardItemModel *model, QString &name)
{
    QStandardItem *rootItem = model->invisibleRootItem();
    return findIndexByNameRecursive(rootItem, name);
}

QModelIndex Widget::findIndexByNameRecursive(QStandardItem *parentItem, QString &name)
{
    int rowCount = parentItem->rowCount();
    for (int row = 0; row < rowCount; ++row)
    {
        QStandardItem *item = parentItem->child(row);
        if (item->text() == name)
        {
            return item->index();
        }

        // Recursively search child items
        QModelIndex index = findIndexByNameRecursive(item, name);
        if (index.isValid())
        {
            return index;
        }
    }
    return QModelIndex(); // Return an invalid index if not found
}


void Widget::on_DisplayselfB_clicked()
{
    QString name="姓名:   "+QString::fromStdString(T->selected->Getname());
    int x=T->selected->Getsex();
    QString sex="性别:    ";
    if(x==0)sex+="女";
    else    sex+="男";
    QString Birthday="生日:   "+QString::fromStdString(T->selected->Getbirthday());
    ui->Screen->append(name);
    ui->Screen->append(sex);
    ui->Screen->append(Birthday);
    Person *t=T->selected->GetP2();
    if(t==NULL)
        ui->Screen->append("无配偶");
    else
    {
        ui->Screen->append("配偶:");
        name="姓名:   "+QString::fromStdString(t->Getname());
        x=t->Getsex();
        sex="性别:    ";
        if(x==0)sex+="女";
        else    sex+="男";
        Birthday="生日:   "+QString::fromStdString(T->selected->GetP2birthday());
        ui->Screen->append(name);
        ui->Screen->append(sex);
        ui->Screen->append(Birthday);
    }
}


void Widget::on_Mofidy_clicked()
{
    bool ok;
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
    string name=getText.toStdString();
    int sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
    int y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
    int m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
    int d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
    T->selected->ResetP(name,sex,y,m,d);
    QItemSelectionModel *selectionModel = ui->treeView->selectionModel();
    QModelIndexList selected = selectionModel->selectedIndexes();
    QModelIndex index = selected.first();
    model->setData(index, getText);
    Widget::on_treeView_clicked();
}


void Widget::on_AddbrotherB_clicked()
{
    bool ok;
    int pd=QInputDialog::getInt(nullptr,"输入整数","如无/有配偶输入0/1:",0,0,1,1,&ok);
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
    string name=getText.toStdString();
    int sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
    int y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
    int m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
    int d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
    Node* temp = new Node(name,sex,y,m,d);
    Person *temp1=NULL;
    if(pd==1)
    {
        getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
        name=getText.toStdString();
        sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
        y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
        m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
        d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
        temp1 =new Person(name,sex,y,m,d);
    }
    T->selected->addbrother(temp,temp1);
    Node* parent=T->selected->Getparent();
    if(parent==NULL)
    {
        QStandardItem *rootItem = model->invisibleRootItem();
        QStandardItem *item1 = new QStandardItem(getText);
        rootItem->appendRow(item1);
    }
    else
    {
        QString pname=QString::fromStdString(parent->Getname());
        QModelIndex index = findIndexByName(model, pname);
        if (index.isValid())
        {
            QStandardItem *newItem = new QStandardItem(getText);
            model->itemFromIndex(index)->appendRow(newItem);
        }
        else
        {
            // Handle the case where the item with the specified name was not found
            QMessageBox::information(this, "Not Found", "Item with the specified name was not found.");
        }
    }
    Widget::on_treeView_clicked();
}


void Widget::on_AddchildB_clicked()
{
    bool ok;
    int pd=QInputDialog::getInt(nullptr,"输入整数","如无/有配偶输入0/1:",0,0,1,1,&ok);
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
    string name=getText.toStdString();
    int sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
    int y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
    int m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
    int d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
    Node* temp = new Node(name,sex,y,m,d);
    Person *temp1=NULL;
    if(pd==1)
    {
        getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
        name=getText.toStdString();
        sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
        y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
        m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
        d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
        temp1 =new Person(name,sex,y,m,d);
    }
    T->selected->addchild(temp,temp1);
    QItemSelectionModel *selectionModel = ui->treeView->selectionModel();
    QModelIndexList selected = selectionModel->selectedIndexes();
    QModelIndex index = selected.first();
    QStandardItem *newItem = new QStandardItem(getText);
    model->itemFromIndex(index)->appendRow(newItem);
    Widget::on_treeView_clicked();
}


void Widget::on_DisplaydireB_clicked()
{
    vector<Node*>  ve;
    vector<Node*>* v=&ve;
    T->DALL(v);
    //ui->Screen->clear();
    for(int i=0;i<v->size();i++)
    {
        if((*v)[i]==NULL)   continue;
        QString s=QString::fromStdString(ve[i]->Getname());
        ui->Screen->append(s);
    }
}


void Widget::on_Change_clicked()
{
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入要切换节点的姓名:",QLineEdit::Normal,"");
    string name=getText.toStdString();
    bool ok=T->CHG(name);
    ui->Screen->clear();
    if(ok)
        ui->Screen->setText("切换成功");
    else
        ui->Screen->setText("切换失败,未找到此节点");

}

//修改配偶
void Widget::on_pushButton_clicked()
{
    bool ok;
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入姓名:",QLineEdit::Normal,"");
    string name=getText.toStdString();
    int sex=QInputDialog::getInt(nullptr,"输入整数","请输入一个性别(女0男1):",0,-100,100,1,&ok);
    int y=QInputDialog::getInt(nullptr,"输入整数","请输入生日年份:",0,-10000,10000,1,&ok);
    int m=QInputDialog::getInt(nullptr,"输入整数","请输入生日月份:",0,1,12,1,&ok);
    int d=QInputDialog::getInt(nullptr,"输入整数","请输入生日日数:",0,1,31,1,&ok);
    T->selected->ResetP2(name,sex,y,m,d);
    Widget::on_treeView_clicked();
}


void Widget::on_CountGen_clicked()
{
    int x=T->COG();
    QString name;
    name+="第";
    name+=QString::number(x);
    name+="代";
    ui->Screen->append(name);
}


void Widget::on_Save_clicked()
{
    bool ok;
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入保存路径:",QLineEdit::Normal,"");
    string path=getText.toStdString();
    replace(path.begin(), path.end(), '\\', '/');
    T->SV(path);
}


void Widget::on_Load_clicked()
{
    QString getText=QInputDialog::getText(nullptr,"输入对话框","请输入导入路径:",QLineEdit::Normal,"");
    string path=getText.toStdString();
    replace(path.begin(), path.end(), '\\', '/');
    T->Load(path);
    Widget::on_update_clicked();
    on_paint_clicked();
}


void Widget::on_Exit_clicked()
{
    close();
}

void Widget::on_update_clicked()
{
    Node* t=T->getRoot();
    vector<Node*> v;
    t->travel(&v);
    for(int i=0;i<v.size();i++)
    {
        Node* parent=v[i]->Getparent();
        QString name=QString::fromStdString(v[i]->Getname());
        if(parent==NULL)
        {
            QStandardItem *rootItem = model->invisibleRootItem();
            QStandardItem *item1 = new QStandardItem(name);
            rootItem->appendRow(item1);
        }
        else
        {
            QString pname=QString::fromStdString(parent->Getname());
            QModelIndex index = findIndexByName(model, pname);
            if (index.isValid())
            {
                QStandardItem *newItem = new QStandardItem(name);
                model->itemFromIndex(index)->appendRow(newItem);
            }
            else
            {
                // Handle the case where the item with the specified name was not found
                QMessageBox::information(this, "Not Found", "Item with the specified name was not found.");
            }
        }
    }
}


void Widget::on_treeView_clicked()
{
    ui->Screen->clear();
    QItemSelectionModel *selectionModel = ui->treeView->selectionModel();
    QModelIndexList selected = selectionModel->selectedIndexes();
    if (!selected.isEmpty())
    {
        QModelIndex index = selected.first();
        QString s=index.data().toString();
        string name=s.toStdString();
        T->CHG(name);
        Widget::on_CountGen_clicked();
        Widget::on_DisplayselfB_clicked();
        Widget::on_DisplaydireB_clicked();
        for(int i=0;i<vvr->size();i++)
        {
            if((*vvr)[i]==NULL) continue;
            QList<QGraphicsItem*> childItems = (*vvr)[i]->childItems();
            for (QGraphicsItem* item : childItems)
            {
                if (QGraphicsTextItem* textItem = dynamic_cast<QGraphicsTextItem*>(item))
                {
                    if(textItem->toPlainText()==s)
                    {
                        for(int i=0;i<(*vvr).size();i++)
                        {
                            if((*vvr)[i]==NULL) continue;
                            (*vvr)[i]->setBrush(Qt::white);
                        }
                        (*vvr)[i]->setBrush(Qt::yellow);
                        break;
                        // ui->graphicsView->centerOn((*vvr)[i]->boundingRect().center());
                        // //ui->graphicsView->scale(2,2);
                        // qreal scaleFactor = 0.5; // 设置缩放比例为
                        // QTransform transform;
                        // transform.scale(scaleFactor, scaleFactor); // 创建缩放变换
                        // ui->graphicsView->setTransform(transform); // 应用变换
                    }
                }
            }
        }


        /*Node* root=T->getRoot();
        int maxdep=root->maxDepth(root);
        vector<Node*> v(1<<maxdep,NULL);
        root->travel1(&v,1);
        for(int i=0;i<v.size();i++)
        {
            if(v[i]!=NULL)
                if(v[i]->Getname()==name)
                {
                    (*vvr)[i]->setBrush(Qt::yellow);
                    scene->addRect((*vvr)[i]->rect());
                }
        }*/
    }
    //on_paint_clicked();
}


void QGraphicsView::wheelEvent(QWheelEvent *event)
{
    // 缩放
    if (event->angleDelta().y() > 0) {
        this->scale(1.2, 1.2); // 放大
    } else {
        this->scale(1.0 / 1.2, 1.0 / 1.2); // 缩小
    }
    event->accept();
}

void Widget::paintrname(MyRectItem* R,string name)
{
    QString qname=QString::fromStdString(name);
    QGraphicsTextItem *textItem=new QGraphicsTextItem;
    textItem->setFont(QFont("Arial", 20));
    textItem->setPlainText(qname);
    textItem->setPos(R->rect().center() - QPointF(textItem->boundingRect().width() / 2, textItem->boundingRect().height() / 2));
    textItem->setZValue(1000);
    textItem->setParentItem(R);
    R->textItem=textItem;
    return;
}


void Widget::on_paint_clicked()
{
    scene->clear();
    Node* root=T->getRoot();
    int maxdep=root->maxDepth(root);
    int x=scene->width()-500;
    int y=scene->height()-500;
    //paintrect(x/2, y/10,"yes");
    vector<Node*> v(1<<maxdep,NULL);
    vector<MyRectItem *> *vr=new vector<MyRectItem *>(1<<maxdep);
    vvr=vr;
    vector<int> vx(1<<maxdep);
    vector<int> vy(1<<maxdep);
    root->travel1(&v,1);
    int py=y/maxdep;
    for(int i=1;i<=maxdep;i++)
    {
        int px=x/((1<<(i-1))+1);
        int cnt=1;
        for(int j=(1<<(i-1));j<(1<<i);j++)
        {
            if(v[j]==NULL)  continue;
            MyRectItem* rect=new MyRectItem(px*cnt-100,py*i-50,200,100);
            connect(rect,&MyRectItem::selectedchanged,this,&Widget::changeselect);
            paintrname(rect,v[j]->Getname());
            scene->addItem(rect);
            scene->addItem(rect->textItem);
            (*vr)[j]=rect;
            QPointF point=rect->rect().center();
            vx[j]=point.x();
            vy[j]=point.y();
            cnt++;
            if(j!=1)
            {
                Mylineitem* line=new Mylineitem((*vr)[j/2],(*vr)[j],vx[j/2],vy[j/2]+50,vx[j],vy[j]-50);
                line->setPen(QPen(Qt::black));
                //scene->addLine(vx[j/2],vy[j/2]+50,vx[j],vy[j]-50,QPen(Qt::black));
                scene->addItem(line);
                //connect((*vvr)[j/2], &MyRectItem::positionChanged, line, &Mylineitem::updateLinePosition);

            }
        }
    }
}

void Widget::changeselect(QString msg)
{
    QModelIndex index = findIndexByName(model, msg);
    // 获取选择模型
    QItemSelectionModel *selectionModel = ui->treeView->selectionModel();
    // 清除当前选择
    selectionModel->clearSelection();
    selectionModel->select(index, QItemSelectionModel::Select); // 选择该项
    ui->treeView->setCurrentIndex(index); // 设置当前索引
    on_treeView_clicked();
}
